package validators

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/locales/zh_Hant_TW"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	uni *ut.UniversalTranslator
	//validate *validator.Validate
	Trans ut.Translator // 全局验证器
)

// Func myvalidator.ValidateMobile
type Func func(fl validator.FieldLevel) bool

// RegisterValidatorFunc 注册自定义校验tag
func RegisterValidatorFunc(v *validator.Validate, trans ut.Translator, tag string, msg string, fn Func) {

	// 注册tag自定义校验
	_ = v.RegisterValidation(tag, validator.Func(fn))
	//自定义错误内容
	_ = v.RegisterTranslation(tag, trans, func(ut ut.Translator) error {
		return ut.Add(tag, "{0}"+msg, true) // see universal-translator for details
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T(tag, fe.Field())
		return t
	})

	return
}

func NewTranslator() error {
	var err error
	//注册翻译器
	en := en.New()
	zh := zh.New()
	zh_hant_tw := zh_Hant_TW.New()
	uni = ut.New(en, zh, zh_hant_tw)

	locale := "zh"

	Trans, _ = uni.GetTranslator("zh")

	//获取gin的校验器
	v, ok := binding.Validator.Engine().(*validator.Validate)
	//注册翻译器
	if ok {
		//RegisterValidatorFunc(v, Trans, "checkMobile", "Not a proper cell phone number", req.CheckMobile)
		//RegisterValidatorFunc(v, Trans, "checkUserNameToPass", "Only English, numbers and _", req.CheckUserNameToPass)

		switch locale {
		case "zh":
			err = zh_translations.RegisterDefaultTranslations(v, Trans)
			break
		case "en":
			err = en_translations.RegisterDefaultTranslations(v, Trans)
			break
		default:
			err = zh_translations.RegisterDefaultTranslations(v, Trans)
			break
		}
	}

	return err

}
